package cz.spock.parser.service;

import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.springframework.stereotype.Service;

import cz.spock.core.service.BaseService;
import cz.spock.exception.InvalidDataException;
import cz.spock.parser.entity.Rule;
import cz.spock.parser.entity.TagPattern;

/**
 *
 * 
 * @author miso
 *
 */
@Service
public class TagPatternService extends BaseService {
    
    
    public TagPattern setRegex(String tag, boolean isRE, TagPattern tp) {
        if(tp == null) return null;
        if(tag == null) return tp;
        if(isRE) {
            if(this.validateRegex(tag)) {
                tp.setRegex(tag);                
            } else {
                throw new InvalidDataException("Given regular expression is invalid.", 400);
            }
        } else {
            tp.setRegex(this.createRegexForGivenString(tag));
        }
        return tp;
    }
    
    public TagPattern addRule(Long rule, TagPattern tp) {
        if(tp == null) return null;
        if(rule == null) return tp;
        tp.getRulesId().add(rule);
        return tp;
    }
    
    public TagPattern removeRule(Long rule, TagPattern tp) {
        if(tp == null) return null;
        if(rule == null) return tp;
        tp.getRulesId().remove(rule);
        return tp;        
    }
    
    public TagPattern save(TagPattern tp) {
        if(tp == null) return null;
        tp.setId(dao.put(tp).getId());
        return tp;
    }
    
    // TODO check whether dao.ofy().find(Rule.class, l); will play because Rule is interface!
    public TagPattern createTransientListOfRules(TagPattern tp) {
        if(tp == null) return null;
        if(tp.getRulesId() == null) return tp;        
        tp.setRules(new ArrayList<Rule>());
        for(Long l : tp.getRulesId()) {
            Rule r = dao.ofy().find(Rule.class, l);
            if(tp != null) tp.getRules().add(r);
        }
        return null;
    }
    
    /**
     * returns true or false if given regex is valid
     * 
     * @param re
     * @return
     */
    public boolean validateRegex(String re) {
        if(re == null) return false;
        try {
            Pattern.compile(re);
        } catch(PatternSyntaxException e) {
            return false;
        }
        return true;
    }
    
    /**
     * returns Pattern.quote()
     * 
     * @param str
     * @return
     */
    public String createRegexForGivenString(String str) {
        if(str == null) return null;
        return Pattern.quote(str);
    }
    

}
